#include <iostream>
#include <pthread.h>
#include <string>
#include <unistd.h>

//全局的锁和条件变量
pthread_mutex_t gmutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t gcond = PTHREAD_COND_INITIALIZER;
const int num = 5;
//线程要执行的代码
void *Wait(void *args)
{
    //将void*类型->char*->string
    std::string name = static_cast<const char *>(args);
    while (true) 
    {
        pthread_mutex_lock(&gmutex); // 加锁

        pthread_cond_wait(&gcond, &gmutex); // 线程在这里等待,需要把条件变量和锁传过去
        //唤醒的线程重新申请锁成功的话从这里继续运行代码
        std::cout << "I am " << name << std::endl;
        // sleep(1);
        pthread_mutex_unlock(&gmutex);
    }
    return nullptr;
}
int main()
{
    pthread_t pthreads[num];
    //创建多个线程
    for (int i = 0; i < num; i++)
    {
        char buf[1024];
        snprintf(buf, sizeof(buf), "Thread-%d", i);
        pthread_create(pthreads + i, nullptr, Wait, (void *)buf);
        usleep(1000);
    }
    sleep(1);

    //唤醒线程
    while(true)
    {
        pthread_cond_broadcast(&gcond);//一次把所有在条件变量等待的线程都唤醒
        // pthread_cond_signal(&gcond);//一次唤醒一个
        usleep(1000000);   //隔多长时间唤醒一个
    }
    for (int i = 0; i < num; i++)
    {
        pthread_join(pthreads[i], nullptr);
    }
    return 0;
}